package com.example.springboottest.example.jedis.pool;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * Jedis 类实现了 java.io.Closeable 接口，故而在 JDK 1.7 或者以上版本中可以使用
 * try-with-resources 语句，在其隐藏的 finally 部分自动调用 close 方法
 */
public class JredisPoolTester {
    public static final int NUM = 200;
    public static final String ZSET_KEY = "zset1";

    //测试删除
    public void testDel() {
        Jedis redis = null;
        try {
            redis = JredisPoolBuilder.getJedis();
            long start = System.currentTimeMillis();
            redis.del(ZSET_KEY);
            long end = System.currentTimeMillis();
            System.out.println("删除 zset1  毫秒数:" + (end - start));
        } finally {
            //使用后一定关闭，还给连接池
            if (redis != null) {
                redis.close();
            }
        }
    }

    //测试创建zset
    public void testSet() {
        testDel();

        try (Jedis redis = JredisPoolBuilder.getJedis()) {
            int loop = 0;
            long start = System.currentTimeMillis();
            while (loop < NUM) {
                redis.zadd(ZSET_KEY, loop, "field-" + loop);
                loop++;
            }
            long end = System.currentTimeMillis();
            System.out.println("设置 zset :" + loop + "次, 毫秒数:" + (end - start));
        }
    }

    //测试查询zset
    public void testGet() {

        try (Jedis redis = JredisPoolBuilder.getJedis()) {
            long start = System.currentTimeMillis();
            Set<String> set = redis.zrange(ZSET_KEY, 0, -1);
            long end = System.currentTimeMillis();
            System.out.println("顺序获取 zset  毫秒数:" + (end - start));
            System.out.println(set.toString());
        }


        try (Jedis redis = JredisPoolBuilder.getJedis()) {
            long start = System.currentTimeMillis();
            Set<String> set = redis.zrevrange(ZSET_KEY, 0, -1);
            long end = System.currentTimeMillis();
            System.out.println("逆序获取 zset  毫秒数:" + (end - start));
            System.out.println(set.toString());
        }
    }
}